

#include "CAudioManager.h"


CAudioManager::CAudioManager()
{
    soundsEnabled = musicEnabled = false;
}

CAudioManager::~CAudioManager()
{
    clear();
}


void CAudioManager::play( QString fileName, double sound )
{
    if ( sound < 0.0 ) sound = 0.0;
    if ( sound > 1.0 ) sound = 1.0;

    if (!soundsEnabled) return;

    int file = -1;
    for ( int i = 0; i < files.size(); i++ )
        if ( files[i].fileName == fileName ) {
            file = i;
            break;
        }

    if ( file == -1 ) {
        QList<CSound*> slt;
        TSound snd = { fileName, slt, Phonon::MediaSource( fileName ) };
        files.append( snd );
        file = files.size() - 1;
    }

    bool noFinished = true;

    for ( int i = 0; i < files[file].sounds.size(); i++ ) {
        if ( files[file].sounds[i]->isFinished() ) {
            files[file].sounds[i]->play( sound );
            noFinished = false;
            break;
        }
    }

    if ( noFinished ) {
        CSound* snd = new CSound( files[file].source );
        files[file].sounds.append(snd);
        files[file].sounds.last()->play( sound );
    }

}

void CAudioManager::clear() {
    for ( int i = 0; i < files.size(); i++ ) {
        for ( int j = 0; j < files[i].sounds.size(); j++ ) {
            delete files[i].sounds[j];
        }
        files[i].sounds.clear();
    }
    files.clear();
}
